package com.book.service.impl;

import com.book.dao.BookClassesDao;
import com.book.dto.BookClassesDto;
import com.book.dto.BookClassesPage;
import com.book.entity.BookClasses;
import com.book.service.BookClassesService;
import com.book.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//错误码从13001开始
@Service
public class BookClassesServiceImpl implements BookClassesService {

    @Autowired
    private BookClassesDao bookClassesDao;

    /**
     * 给这本书添加他的分类信息
     * @param bookId
     * @param classId
     * @return
     */
    @Override
    public ResponseResult addBookClasses(int bookId, List<Integer> classId) {
        try {
            for (Integer bookClassId : classId) {
                BookClasses bookClasses = new BookClasses();
                bookClasses.setBookId(bookId);
                bookClasses.setClassId(bookClassId);
                bookClassesDao.insert(bookClasses);
            }
            return new ResponseResult(200,"添加分类信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(13001,"添加分类信息失败");
        }
    }

    /**
     * 根据bookId获取书籍与分类对应的信息列表
     * @param bookClassesPage
     * @return
     */
    @Override
    public ResponseResult getBookClasses(BookClassesPage bookClassesPage) {
        try {
            PageHelper.startPage(bookClassesPage.getCurrentPage(),bookClassesPage.getPageSize());
            List<BookClassesDto> bookClassesDtoList = bookClassesDao.getBookClasses(bookClassesPage.getBookId());
            PageInfo<BookClassesDto> classesDtoPageInfo = new PageInfo<>(bookClassesDtoList);

            if(bookClassesPage.getCurrentPage()>classesDtoPageInfo.getPages()){
                PageHelper.startPage(classesDtoPageInfo.getPages(),bookClassesPage.getPageSize());
                bookClassesDtoList = bookClassesDao.getBookClasses(bookClassesPage.getBookId());
                classesDtoPageInfo = new PageInfo<>(bookClassesDtoList);
            }
            return new ResponseResult(200,"查询书籍分类信息成功",classesDtoPageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(13002,"查询书籍分类信息失败");
        }
    }


    /**
     * 根据id删除这个书籍<->分类信息
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteClassesById(int id) {
        try {
            bookClassesDao.deleteById(id);
            return new ResponseResult(200,"删除该书籍分类信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(13003,"删除该书籍分类信息失败");
        }
    }
}
